package net.xxcl.kygl.controller;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import net.xxcl.kygl.model.ProjectForUser;
import net.xxcl.kygl.pojo.Criteria;
import net.xxcl.kygl.pojo.Project;
import net.xxcl.kygl.pojo.User;
import net.xxcl.kygl.service.ProjectService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * User: 夏汛
 * Date: 12-5-16
 * Time: 上午10:16
 */
@Controller
@RequestMapping("/project")
public class ProjectController {
    @Autowired
    private ProjectService projectService;

    /**
     * 根据主键查找课题详细信息
     * @param id
     * @return
     */
    @RequestMapping(value = "/selectById",method= RequestMethod.POST)
    public @ResponseBody Map<String,Object> selectByid(@RequestParam(value = "id") Integer id){
        Map<String,Object> responseMap = new HashMap<String, Object>();
        Project project = projectService.selectByPrimaryKey(id);
        List<Map> users = projectService.getUserByProjectId(id);
        if(users.get(0).get("deptname")!=null){
            project.setDeptname((String) users.get(0).get("deptname"));
        }
        StringBuffer sb = new StringBuffer();
        for(Map user:users){
            if((Boolean)user.get("iscolleague")){
                sb.append(","+user.get("username"));
            } else {
                sb.append(",("+user.get("username")+")");
            }
        }
        project.setNames(sb.substring(1));
        responseMap.put("key",project);
        return responseMap;
    }

    /**
     * 获取课题分页
     * @param start
     * @param limit
     * @return
     */
    @RequestMapping(value = "/list",method= RequestMethod.POST)
    public @ResponseBody
    Map<String,Object> list(@RequestParam(value = "start") Integer start,
                            @RequestParam(value = "limit") Integer limit){
        Map<String,Object> responseMap = new HashMap<String, Object>();
        Criteria criteria = new Criteria();
        criteria.put("inschool",1);
        int total = projectService.countByExample(criteria);
        if(start!=null && limit!=null){
            criteria.setMysqlOffset(start);
            criteria.setMysqlLength(limit);
        }
        List<Project> list = projectService.selectByExample(criteria);
        responseMap.put("total", total);
        responseMap.put("rows",list);
        return responseMap;
    }

    /**
     * 获取用户参与的院级课题
     * @return
     */
    @RequestMapping(value = "/listProjectForUser",method= RequestMethod.POST)
    public @ResponseBody Map<String,Object> listProjectForUser(@RequestParam("start") Integer start,@RequestParam("limit") Integer limit,
                                                               HttpServletRequest request,HttpServletResponse response){
        Map<String,Object> responseMap = new HashMap<String, Object>();
        User user = (User)request.getSession().getAttribute("user");
        Criteria criteria = new Criteria();
        criteria.put("inschool",1);
        criteria.setOrderByClause("t_project.id desc");
        criteria.put("userid",user.getId());
        int total = projectService.countByUserId(criteria);
        List<ProjectForUser> list = projectService.selectByUserId(criteria);
        responseMap.put("total",total);
        responseMap.put("rows",list);
        return responseMap;
    }

    /**
     * 查询某用户参与的课题
     * @return
     */
    @RequestMapping(value = "/listKtcxbyuser",method= RequestMethod.POST)
    public @ResponseBody Map<String,Object> listKtcxbyuser(@RequestParam("start") Integer start,
                                     @RequestParam("limit") Integer limit,@RequestParam("userid") Integer userid,
                                     @RequestParam(value = "startTime",required = false) String startTime,
                                     @RequestParam(value = "endTime",required = false) String endTime,
                                     HttpServletRequest request,HttpServletResponse response){
        Map<String,Object> responseMap = new HashMap<String, Object>();
        Criteria criteria = new Criteria();
        if(!(startTime==null || startTime.equals(""))) criteria.put("startTime",startTime);
        if(!(endTime==null || endTime.equals(""))) criteria.put("endTime",endTime);
        criteria.setOrderByClause("t_project.id desc");
        criteria.put("userid",userid);
        criteria.put("kyktxxstate", 1);
        int total = projectService.countByUserId(criteria);
        List<ProjectForUser> list = projectService.selectByUserId(criteria);
        responseMap.put("total",total);
        responseMap.put("rows",list);
        return responseMap;
    }

    /**
     * 获取申报课题分页
     * @param start
     * @param limit
     * @return
     */
    @RequestMapping(value = "/listForSbkt",method= RequestMethod.POST)
    public @ResponseBody
    Map<String,Object> listForSbkt(@RequestParam(value = "start") Integer start,
                            @RequestParam(value = "limit") Integer limit){
        Map<String,Object> responseMap = new HashMap<String, Object>();
        Criteria criteria = new Criteria();
        criteria.setMysqlOffset(start);
        criteria.setMysqlLength(limit);
        criteria.setOrderByClause("t_project.id desc");
        criteria.put("sbktstate",0);
        criteria.put("inschool",1);
        int total = projectService.countByExample(criteria);
        List<Project> list = projectService.selectByExample(criteria);

        for(Project project:list){
            List<Map> users = projectService.getUserByProjectId(project.getId());
            if(users.get(0).get("deptname")!=null){
                project.setDeptname((String) users.get(0).get("deptname"));
            }
            StringBuffer sb = new StringBuffer();
            for(Map user:users){
                if((Boolean)user.get("iscolleague")){
                    sb.append(","+user.get("username"));
                } else {
                    sb.append(",("+user.get("username")+")");
                }
            }
            project.setNames(sb.substring(1));
        }

        responseMap.put("total",total);
        responseMap.put("rows",list);
        return responseMap;
    }

    /**
     * 获取计划任务书审核分页
     * @param start
     * @param limit
     * @return
     */
    @RequestMapping(value = "/listForJhrws",method= RequestMethod.POST)
    public @ResponseBody
    Map<String,Object> listForJhrws(@RequestParam(value = "start") Integer start,
                                     @RequestParam(value = "limit") Integer limit){
        Map<String,Object> responseMap = new HashMap<String, Object>();
        Criteria criteria = new Criteria();
        criteria.put("state", 4);
        criteria.put("inschool", 1);
        criteria.setOrderByClause("t_project.id desc");
        int total = projectService.countByExample(criteria);
        criteria.setMysqlOffset(start);
        criteria.setMysqlLength(limit);
        List<Project> list = projectService.selectByExample(criteria);

        for(Project project:list){
            List<Map> users = projectService.getUserByProjectId(project.getId());
            if(users.get(0).get("deptname")!=null){
                project.setDeptname((String) users.get(0).get("deptname"));
            }
            StringBuffer sb = new StringBuffer();
            for(Map user:users){
                if((Boolean)user.get("iscolleague")){
                    sb.append(","+user.get("username"));
                } else {
                    sb.append(",("+user.get("username")+")");
                }
            }
            project.setNames(sb.substring(1));
        }

        responseMap.put("total",total);
        responseMap.put("rows",list);
        return responseMap;
    }

    /**
     * 获取中期报告检查分页
     * @param start
     * @param limit
     * @return
     */
    @RequestMapping(value = "/listForZqjcsh",method= RequestMethod.POST)
    public @ResponseBody
    Map<String,Object> listForZqjcsh(@RequestParam(value = "start") Integer start,
                                   @RequestParam(value = "limit") Integer limit){
        Map<String,Object> responseMap = new HashMap<String, Object>();
        Criteria criteria = new Criteria();
        criteria.put("inschool",1);
        criteria.put("state", 5);
        criteria.setOrderByClause("t_project.id desc");
        int total = projectService.countByExample(criteria);
        criteria.setMysqlOffset(start);
        criteria.setMysqlLength(limit);
        List<Project> list = projectService.selectByExample(criteria);
        for(Project project:list){
            List<Map> users = projectService.getUserByProjectId(project.getId());
            if(users.get(0).get("deptname")!=null){
                project.setDeptname((String) users.get(0).get("deptname"));
            }
            StringBuffer sb = new StringBuffer();
            for(Map user:users){
                if((Boolean)user.get("iscolleague")){
                    sb.append(","+user.get("username"));
                } else {
                    sb.append(",("+user.get("username")+")");
                }
            }
            project.setNames(sb.substring(1));
        }
        responseMap.put("total",total);
        responseMap.put("rows",list);
        return responseMap;
    }

    /**
     * 获取结题报告专家指定分页
     * @param start
     * @param limit
     * @return
     */
    @RequestMapping(value = "/listForJtyszjzd",method= RequestMethod.POST)
    public @ResponseBody Map<String,Object> listForJtyszjzd(@RequestParam(value = "start") Integer start,
                                   @RequestParam(value = "limit") Integer limit){
        Map<String,Object> responseMap = new HashMap<String, Object>();
        Criteria criteria = new Criteria();
        criteria.setOrderByClause("t_project.id desc");
        criteria.put("jtpsyjstate",8);
        criteria.put("inschool", 1);
        int total = projectService.countByExample(criteria);
        criteria.setMysqlOffset(start);
        criteria.setMysqlLength(limit);
        List<Project> list = projectService.selectByExample(criteria);
        for(Project project:list){
            List<Map> users = projectService.getUserByProjectId(project.getId());
            if(users.get(0).get("deptname")!=null){
                project.setDeptname((String) users.get(0).get("deptname"));
            }
            StringBuffer sb = new StringBuffer();
            for(Map user:users){
                if((Boolean)user.get("iscolleague")){
                    sb.append(","+user.get("username"));
                } else {
                    sb.append(",("+user.get("username")+")");
                }
            }
            project.setNames(sb.substring(1));
        }
        responseMap.put("total",total);
        responseMap.put("rows",list);
        return responseMap;
    }

    /**
     * 获取课题信息查询分页
     * @param start
     * @param limit
     * @param iscross
     * @param name
     * @param projectType
     * @return
     */
    @RequestMapping(value = "/listForKyktxx",method= RequestMethod.POST)
    public @ResponseBody Map<String,Object> listForKyktxx(@RequestParam(value = "start") Integer start,
                                        @RequestParam(value = "limit") Integer limit,
                                        @RequestParam(value = "iscross",required = false) Integer iscross,
                                        @RequestParam(value = "name",required = false) String name,
                                        @RequestParam(value = "projectType",required = false) Integer projectType,
                                        @RequestParam(value = "startTime",required = false) String startTime,
                                        @RequestParam(value = "endTime",required = false) String endTime){
        Map<String,Object> responseMap = new HashMap<String, Object>();
        Criteria criteria = new Criteria();

        //设置查询条件
        if(!(name==null || name.equals(""))) criteria.put("blurredName","%"+name+"%");
        if(!(startTime==null || startTime.equals(""))) criteria.put("startTime",startTime);
        if(!(endTime==null || endTime.equals(""))) criteria.put("endTime",endTime);
        criteria.put("iscross",iscross);
        criteria.put("projecttype",projectType);

        criteria.put("kyktxxstate", 1);
        criteria.setOrderByClause("t_project.id desc");
        int total = projectService.countByExample(criteria);
        criteria.setMysqlOffset(start);
        criteria.setMysqlLength(limit);
        List<Project> list = projectService.selectByExample(criteria);
        for(Project project:list){
            List<Map> users = projectService.getUserByProjectId(project.getId());
            if(users.get(0).get("deptname")!=null){
                project.setDeptname((String) users.get(0).get("deptname"));
            }
            StringBuffer sb = new StringBuffer();
            for(Map user:users){
                if((Boolean)user.get("iscolleague")){
                    sb.append(","+user.get("username"));
                } else {
                    sb.append(",("+user.get("username")+")");
                }
            }
            project.setNames(sb.substring(1));
        }
        responseMap.put("total",total);
        responseMap.put("rows",list);
        return responseMap;
    }

    /**
     * 申报课题保存
     * @param request
     * @param response
     */
    @RequestMapping(value="/save",method= RequestMethod.POST)
    public void save(MultipartHttpServletRequest request,HttpServletResponse response){
        MultipartFile file = request.getFile("file");
        response.setContentType("text/html");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = null;
        User user = (User) request.getSession().getAttribute("user");
        try{
            out = response.getWriter();
            if(!file.isEmpty()){
                String[] fileNameArray = file.getOriginalFilename().split("\\.");
                if(!(fileNameArray.length>1
                        && (fileNameArray[fileNameArray.length-1].equalsIgnoreCase("rar")
                        || fileNameArray[fileNameArray.length-1].equalsIgnoreCase("zip")
                        || fileNameArray[fileNameArray.length-1].equalsIgnoreCase("doc")
                        || fileNameArray[fileNameArray.length-1].equalsIgnoreCase("docx")
                        || fileNameArray[fileNameArray.length-1].equalsIgnoreCase("pdf")))){
                    out.print("{'info':'只支持word、pdf文件和zip、rar格式的压缩文件'}");
                    return;
                }
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy年");
                SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy");
                SimpleDateFormat sdf3 = new SimpleDateFormat("-yyyy-MM-dd");

                String uploadDate = sdf.format(new Date());
                String projectName = request.getParameter("name");
                String filePath = "upload" + File.separator
                       + uploadDate + File.separator + "科研课题" + File.separator + "院级课题" + File.separator
                       + UUID.randomUUID() + File.separator + projectName + File.separator;
                String fileDate = sdf3.format(new Date());
                String fileTrueName = file.getOriginalFilename();
                int ch = fileTrueName.lastIndexOf(".");
                String fileName = fileTrueName.substring(0,ch) + fileDate + fileTrueName.substring(ch);

                File saveFile = new File(request.getSession().getServletContext().getRealPath("/") +
                        filePath + File.separator + fileName);
                FileUtils.writeByteArrayToFile(saveFile,file.getBytes());
                Project project = new Project();
                project.setPlanendtime(sdf2.parse(request.getParameter("plantime")));
                project.setName(projectName);
                //状态设置为0，提交申报书
                project.setState(0);
                project.setFilepath(filePath);
                project.setFilename(fileName);
                project.setReporttime(new Date());
                project.setProjecttype(Integer.parseInt(request.getParameter("projectTypeId")));
                projectService.addProject(project,request.getParameter("ids"));
                out.print("{'success':'true','info':'课题申报已提交！'}");
            }
        } catch (Exception e){
            e.printStackTrace();
            out.print("{'info':'课题申报提交失败'}");
        }
    }

    /**
     * 课题是否同意立项
     * @param isagree
     * @param projectid
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/submitProjectLx",method= RequestMethod.POST)
    public @ResponseBody Map<String,Object> submitProjectLx(
            @RequestParam(value = "isagree") Boolean isagree,@RequestParam(value = "projectid") Integer projectid,
            HttpServletRequest request,HttpServletResponse response){
        Map<String,Object> responseMap = new HashMap<String, Object>();
        try{
            Project project = new Project();
            project.setId(projectid);
            if(isagree){
                //申报通过
                project.setState(3);
                project.setApprovaltime(new Date());
            } else {
                //申报不通过
                project.setState(2);
            }
            projectService.updateByPrimaryKeySelective(project);
            responseMap.put("success", "true");
            if(isagree){
                responseMap.put("info", "课题立项");
            } else {
                responseMap.put("info", "课题不同意立项");
            }
        } catch (Exception e){
            e.printStackTrace();
            responseMap.put("info","课题状态改变失败");
        }
        return responseMap;
    }

    /**
     * 课题是否同意结题
     * @param isagree
     * @param projectid
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/submitProjectJt",method= RequestMethod.POST)
    public @ResponseBody Map<String,Object> submitProjectJt(
            @RequestParam(value = "isagree") Boolean isagree,@RequestParam(value = "projectid") Integer projectid,
            HttpServletRequest request,HttpServletResponse response){
        Map<String,Object> responseMap = new HashMap<String, Object>();
        try{
            Project project = new Project();
            project.setId(projectid);
            if(isagree){
                //结题通过
                project.setState(11);
                project.setEndtime(new Date());
            } else {
                //结题不通过
                project.setState(10);
            }
            projectService.updateByPrimaryKeySelective(project);
            responseMap.put("success", "true");
            if(isagree){
                responseMap.put("info", "课题已经结题");
            } else {
                responseMap.put("info", "课题不同意结题");
            }
        } catch (Exception e){
            e.printStackTrace();
            responseMap.put("info","课题状态改变失败");
        }
        return responseMap;
    }

    /**
     * 计划任务书是否通过
     * @param isagree
     * @param projectid
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/submitProjectJhrws",method= RequestMethod.POST)
    public @ResponseBody Map<String,Object> submitProjectJhrws(
            @RequestParam(value = "isagree") Boolean isagree,@RequestParam(value = "projectid") Integer projectid,
            HttpServletRequest request,HttpServletResponse response){
        Map<String,Object> responseMap = new HashMap<String, Object>();
        try{
            Project project = new Project();
            project.setId(projectid);
            if(isagree){
                //计划任务书通过
                project.setState(12);
            } else {
                //计划任务书不通过
                project.setState(13);
            }
            projectService.updateByPrimaryKeySelective(project);
            responseMap.put("success", "true");
            if(isagree){
                responseMap.put("info", "计划任务书检查通过");
            } else {
                responseMap.put("info", "计划任务书检查不通过");
            }
        } catch (Exception e){
            e.printStackTrace();
            responseMap.put("info","课题状态改变失败");
        }
        return responseMap;
    }

    /**
     * 中期检查是否通过
     * @param isagree
     * @param projectid
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/submitProjectZqjc",method= RequestMethod.POST)
    public @ResponseBody Map<String,Object> submitProjectZqjc(
            @RequestParam(value = "isagree") Boolean isagree,@RequestParam(value = "projectid") Integer projectid,
            HttpServletRequest request,HttpServletResponse response){
        Map<String,Object> responseMap = new HashMap<String, Object>();
        try{
            Project project = new Project();
            project.setId(projectid);
            if(isagree){
                //中期检查通过
                project.setState(7);
            } else {
                //中期检查不通过
                project.setState(6);
            }
            projectService.updateByPrimaryKeySelective(project);
            responseMap.put("success", "true");
            if(isagree){
                responseMap.put("info", "中期检查通过");
            } else {
                responseMap.put("info", "中期检查不通过");
            }
        } catch (Exception e){
            e.printStackTrace();
            responseMap.put("info","课题状态改变失败");
        }
        return responseMap;
    }

    /**
     * 改变课题状态
     * @param projectid
     * @param state
     */
    @RequestMapping(value = "/changeState",method= RequestMethod.POST)
    public @ResponseBody Map<String,Object> changeState(@RequestParam(value = "projectid") Integer projectid,
                                                        @RequestParam(value = "state") Integer state){
        Map<String,Object> responseMap = new HashMap<String, Object>();
        try{
            Project project = projectService.selectByPrimaryKey(projectid);
            int oldState = project.getState();
            if((oldState==3 || oldState==6) && state==5){
                project.setState(state);
                project.setMiddletime(new Date());
                projectService.updateByPrimaryKeySelective(project);
                responseMap.put("info","申请中期检查成功，请等待");
            }
            if((oldState==3 || oldState==7 || oldState==10) && state==8){
                project.setState(state);
                projectService.updateByPrimaryKeySelective(project);
                responseMap.put("info","申请结题成功，请等待");
            }
            responseMap.put("success", "true");
        } catch (Exception e){
            e.printStackTrace();
            responseMap.put("info","课题状态改变失败");
        }
        return responseMap;
    }

    @RequestMapping(value="/import",method=RequestMethod.POST)
    public void importFromExcel(MultipartHttpServletRequest request,HttpServletResponse response){
        MultipartFile file = request.getFile("file");
        response.setContentType("text/html");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            if(!file.isEmpty()){
                String fileHz = "";
                //如果文件类型是excel 2003，后缀名设置为.xls，excel 2007则设置为.xlsx
                if(file.getContentType().equals("application/vnd.ms-excel")){
                    fileHz = ".xls";
                } else {
                    out.print("{'info':'暂只能支持excel 2003格式的文件'}");
                    return;
                }

                String filePath = request.getSession().getServletContext().getRealPath("/");
                String fileName = UUID.randomUUID() + fileHz;

                File dirPath = new File(filePath);
                if (!dirPath.exists()) {
                    dirPath.mkdirs();
                }
                String realPath = filePath+File.separator+"temp"+File.separator+fileName;
                File saveFile = new File(realPath);
                FileUtils.writeByteArrayToFile(saveFile, file.getBytes());
                out.print("{'info':'"+importToDB(realPath)+"'}");
            }
        } catch(Exception e) {
            e.printStackTrace();
            out.print("{'info':'导入失败！'");
        } finally {
            if(out!=null){
                out.flush();
                out.close();
            }
        }
        return;
    }

    private String importToDB(String fileToBeRead){
        String message = "";    //返回的信息
        int totalSuccess = 0;   //导入成功条数
        int total = 0;          //总条数
        String errorLine = "";  //错误的行号
        try{
            //创建对工作薄的引用
            Workbook book = Workbook.getWorkbook(new File(fileToBeRead));
            //创建对第一张工作表的引用
            Sheet sheet = book.getSheet(0);
            //获取有效行数（可能中间有空行，因此不等于总条数）
            int rowNumber = sheet.getRows();
            //i=1开始循环，默认第一行为标题行，不读取
            for(int i=1;i<rowNumber;i++){
                //获取行数据
                Cell[] cells = sheet.getRow(i);
                //第一列为设置的必选，如果该列没有内容，那么认为该行是空行
                if(cells[0].getContents()==null || cells[0].getContents().equals("")){
                    continue;
                }
                total += 1;
                try{
                    projectService.saveExcelRow(cells);
                    totalSuccess += 1;
                } catch (RuntimeException e){
                    //errorLine += ","+(total+1);
                    message += "第"+(total+1)+"行导入失败，原因：<br />" + e.getMessage() + "<br />";
                }
            }
        } catch (Exception e){
            e.printStackTrace();
        }
        message = "导入成功"+totalSuccess+"条记录！<br />" + message;
//        if(!errorLine.equals("")){
//            //用substring(1)是为了去掉最前边的逗号
//            message += "导入失败"+(total-totalSuccess)+"条记录!<br />失败的行："+errorLine.substring(1);
//        }
        return message;
    }

    @RequestMapping(value = "/addDescriptionAndRemarks",method= RequestMethod.POST)
    public @ResponseBody Map<String,Object> addRemarks(@RequestParam(value = "projectid") Integer projectid,
                            @RequestParam(value = "description",required = false) String description,
                            @RequestParam(value = "remarks",required = false) String remarks){
        Map<String,Object> responseMap = new HashMap<String, Object>();
        try{
            Project project = new Project();
            project.setId(projectid);
            if(!(description==null || description.equals(""))){
                project.setDescription(description);
            } else if(!(remarks==null || remarks.equals(""))){
                project.setRemarks(remarks);
            } else {
                responseMap.put("info","添加失败");
                return responseMap;
            }
            projectService.updateByPrimaryKeySelective(project);
            responseMap.put("info","提交成功");
            responseMap.put("success", "true");
        } catch (Exception e){
            e.printStackTrace();
            responseMap.put("info","添加失败");
        }
        return responseMap;
    }
}
